﻿using UnityEngine;
using System.Collections;
using Helper;

public class TransmitEffect : MonoBehaviour {
	[SerializeField] string targetRendererName;
	[SerializeField] string targetPosName;
	SkinnedMeshRenderer targetRenderer;
	Transform targetPos;

	[SerializeField] float moveTimeRate = 3f;
	[SerializeField] float periodNum = 3f;
	[SerializeField] float amplitude = 1f;
	//粒子运动开始的时间
	[SerializeField] float startTime = 0.5f;

	ParticleSystem particleSys;
	ParticleSystemRenderer parSysRenderer;
	ParticleSystem.Particle[] regionParticlesPos;
	float lastTime = 0f;
	bool isStartMoving = false;

	void Awake () {
		targetRenderer = ItemManager.GetItemFlag (targetRendererName).GetComponent<SkinnedMeshRenderer> ();
		targetPos = ItemManager.GetItemFlag (targetPosName).transform;
		particleSys = GetComponent<ParticleSystem> ();
		parSysRenderer = particleSys.GetComponent<ParticleSystemRenderer> ();
		targetRenderer.enabled = false;
		ParticleSystem.ShapeModule shapeModule = particleSys.shape;
		shapeModule.mesh = targetRenderer.sharedMesh;
	}

	void Update () {
		lastTime += Time.deltaTime;
		if (lastTime <= startTime) {
			return;
		}
		if (lastTime >= particleSys.duration) {
			//Destroy (gameObject);
			gameObject.SetActive(false);
			return;
		}
		particlesMove ();
	}

	void particlesMove(){
		int particlesNum = particleSys.particleCount;
		ParticleSystem.Particle[] particles = new ParticleSystem.Particle[particlesNum];
		particleSys.GetParticles (particles);

		if (!isStartMoving) {
			isStartMoving = true;
			regionParticlesPos = new ParticleSystem.Particle[particlesNum];
			particleSys.GetParticles (regionParticlesPos);
			parSysRenderer.renderMode = ParticleSystemRenderMode.Stretch;
			print (regionParticlesPos);
		} else if (regionParticlesPos == null || regionParticlesPos.Length < particlesNum) {
			return;
		}

		for(int i = 0; i<particlesNum; i++) {
			Vector3 curPos = MyTween.GetPosInSin(particles[i].position, targetPos.position,
				periodNum / moveTimeRate * (1f - particles[i].lifetime / particles[i].startLifetime),
				amplitude: amplitude, periodNum: periodNum);
			particles [i].velocity = (curPos - particles [i].position) / Time.deltaTime;
			particles [i].position = curPos;
		}
		particleSys.SetParticles (particles, particlesNum);
	}

	void OnDisable(){
		targetRenderer.enabled = true;
	}
	void OnEnable(){
		targetRenderer.enabled = false;
		lastTime = 0f;
		isStartMoving = false;
		parSysRenderer.renderMode = ParticleSystemRenderMode.Billboard;
	}
}
